<script setup lang="ts">
import TableView from '@/components/TableView.vue'
import {
  NButton,
  NDataTable,
  NPagination,
  useMessage,
  type DataTableColumns,
  NSpace,
  NInput,
  NSelect,
  NDatePicker,
  NForm,
  NFormItem,
  NUpload
} from 'naive-ui'
import { h, ref, reactive, watch } from 'vue'
import router from '@/router'
import { useRoute } from 'vue-router'
import { sendRequest } from '@/utils/api'
import { useViewerStore } from '../Common/store'

const message = useMessage()
const route = useRoute()
const useStore = useViewerStore()

const rowKey: any = (e: any) => e.id || ''
const columns: DataTableColumns = [
  {
    title: '序号',
    key: 'orderIndex',
    render: (_, i) => {
      return ++i + (paginationReactive.page - 1) * paginationReactive.pageSize
    },
    width: '5rem',
    align: 'center'
  },
  {
    title: '考核名称',
    key: 'assessName',
    width: '20rem',
    align: useStore.isCenter,
    ellipsis: {
      tooltip: {
        contentStyle: {
          maxWidth: '400rem'
        }
      }
    }
  },
  {
    title: '开始时间',
    key: 'startTime',
    width: '5rem',
    align: useStore.isCenter
  },
  {
    title: '截止时间',
    key: 'updateTime',
    width: '10rem',
    align: useStore.isCenter
  },
  {
    title: '考核状态',
    key: 'processStatus',
    width: '10rem',
    align: useStore.isCenter
  },
  {
    title: '考核人数',
    key: 'num',
    width: '10rem',
    align: useStore.isCenter
  },
  {
    title: '是否下发',
    key: 'nodeTime',
    width: '10rem',
    align: useStore.isCenter,
    render(e: any) {
      return e.sendFlag == 1 ? '已下发' : '未下发'
    }
  },
  {
    title: '操作',
    key: 'action',
    width: '10rem',
    align: useStore.isCenter,
    fixed: 'right',
    render: (e: any) =>
      h(
        'div',
        {
          style: {
            display: 'flex'
          }
        },
        {
          default: () => [
            h(
              NUpload,
              {
                showFileList: false,
                customRequest: (c: any) => handleUpload(c, e.id),
                style: {
                  display: !e.fileId ? 'inline-flex' : 'none',
                  color: 'green',
                  width: 'auto'
                }
              },
              {
                default: () =>
                  h(
                    NButton,
                    {
                      type: 'primary',
                      quaternary: true
                    },
                    {
                      default: () => '上传'
                    }
                  )
              }
            ),
            h(
              NButton,
              {
                type: 'primary',
                quaternary: true,
                style: {
                  display: e.fileId ? 'inline-flex' : 'none'
                },
                onClick: () => handleSend(e)
              },
              {
                default: () => '下发'
              }
            ),
            h(
              NButton,
              {
                type: 'primary',
                quaternary: true,
                onClick: () => handleDetail(e)
              },
              {
                default: () => '详情'
              }
            ),
            h(
              NButton,
              {
                type: 'primary',
                quaternary: true,
                onClick: () => handleExport(e)
              },
              {
                default: () => '导出'
              }
            )
          ]
        }
      )
  }
]

//筛选条件
const formValue = reactive({
  assessName: null, //考核名称
  processStatusCode: null, //考核状态编码
  sendFlag: null, //是否下发
  startTime: null //年份
})
const paginationReactive = reactive({
  page: 1,
  pageSize: 10,
  showSizePicker: true,
  pageSizes: [10, 20, 50, 100, 500],
  itemCount: 0,
  onChange: (page: number) => {
    paginationReactive.page = page
    queryTableData()
  },
  onUpdatePageSize: (pageSize: number) => {
    paginationReactive.pageSize = pageSize
    paginationReactive.page = 1
    queryTableData()
  }
})

const isSendList = [
  {
    value: '0',
    label: '未下发'
  },
  {
    value: '1',
    label: '已下发'
  }
]

const statusList = ref()
const getStatus = async () => {
  const [error, res] = await sendRequest({
    module: 'office',
    api: 'roomType',
    override: {
      params: {
        dicCode: 'A03'
      }
    }
  })
  if (error) return message.error(error.message)
  if (res.code !== 0) return message.error(res.msg)
  statusList.value = []
  res.data.map((i: any) => {
    statusList.value.push({
      label: i.dicName,
      value: i.dicCode
    })
  })
}
getStatus()

//上传
const fileId = ref()
async function commonUpload(data: any) {
  tableLoading.value = true
  const fileData = new FormData()
  fileData.append('file', data.file as File)
  const [error, res] = await sendRequest({
    module: 'upload',
    api: 'uploadFile',
    override: {
      data: fileData
    }
  })
  if (error) return message.error(error.message)
  fileId.value = res.data?.fileId
}

const handleUpload = async ({ file }: any, id: any) => {
  await commonUpload(file)
  const [error, res] = await sendRequest({
    module: 'exam',
    api: 'sendUpload',
    override: {
      params: {
        id: id,
        fileId: fileId.value
      }
    }
  })
  if (error) return message.error(error.message)
  if (res.code !== 0) return message.error('上传失败')
  message.success('上传成功')
  queryTableData(true)
  tableLoading.value = false
}

//下发
const handleSend = async (val: any) => {
  tableLoading.value = true
  const [error, res] = await sendRequest({
    module: 'exam',
    api: 'sendSend',
    override: {
      params: {
        assessId: val?.id
      }
    }
  })
  if (error) return message.error(error.message)
  message.success(res.msg)
  queryTableData(true)
  tableLoading.value = false
}

//详情
const handleDetail = (val: any) => {
  console.log(val.id)
  router.push({
    path: '/OA/Examination/SendDetail',
    query: {
      id: val?.id
    }
  })
}

//导出
function download(headers: any, data: any, name?: string) {
  const val = headers['content-disposition']?.match(/(?<=filename=)(.*)/)
  let filename = val ? decodeURIComponent(val[0]) : name + '.zip'
  const a = document.createElement('a')
  let binaryData = []
  binaryData.push(data)
  a.href = window.URL.createObjectURL(new Blob(binaryData))
  a.download = filename
  a.click()
  window.URL.revokeObjectURL(a.href)
}
const exportLoading = ref(false)
async function handleExport(val: any) {
  exportLoading.value = true
  const [error, data, headers] = await sendRequest({
    module: 'exam',
    api: 'sendExport',
    override: {
      params: {
        assessId: val?.id
      }
    }
  })
  if (error) return message.error(error.message)
  download(headers, data, '成员考核数据')
  exportLoading.value = false
}

//表格数据
const tableLoading = ref(false)
const tableData: any = ref([])
const queryTableData = async (resetPage = false) => {
  if (resetPage) paginationReactive.page = 1
  tableLoading.value = true
  const [error, res] = await sendRequest({
    module: 'exam',
    api: 'sendList',
    override: {
      params: {
        ...formValue,
        page: paginationReactive.page,
        limit: paginationReactive.pageSize
      }
    }
  })
  tableLoading.value = false
  if (error) return message.error(error.message)
  paginationReactive.itemCount = res.data?.totalCount
  const tmp: any = res.data
  tableData.value = tmp?.list
}

watch(
  () => route.path,
  () => {
    if (route.path == '/OA/Examination/SendList') queryTableData()
  },
  { deep: true, immediate: true }
)
</script>

<template>
  <TableView class="table">
    <template #form>
      <NSpace justify="space-between">
        <NForm :show-feedback="false" label-placement="left" inline>
          <NSpace align="start">
            <NFormItem label="名称搜索:">
              <NInput clearable placeholder="请输入名称" v-model:value="formValue.assessName" />
            </NFormItem>
            <NFormItem label="年份选择:">
             <NDatePicker input-readonly class="commonWidth" type="year" v-model:formatted-value="formValue.startTime" clearable />
            </NFormItem>
            <NFormItem label="考核状态:">
              <NSelect clearable placeholder="请选择考核状态" style="width: 180rem" :options="statusList"
                v-model:value="formValue.processStatusCode" />
            </NFormItem>
            <NFormItem label="是否下发:">
              <NSelect clearable placeholder="请选择是否下发" style="width: 180rem" :options="isSendList"
                v-model:value="formValue.sendFlag" />
            </NFormItem>
            <NButton type="primary" ghost @click="queryTableData(true)">
              查询
            </NButton>
          </NSpace>
        </NForm>
      </NSpace>
    </template>

    <template #table="props">
      <NDataTable v-bind="props" :bordered="false" :row-key="rowKey" :columns="columns" :data="tableData"
        :loading="tableLoading" />
    </template>

    <template #pagination>
        <NPagination :page-sizes="paginationReactive.pageSizes" :item-count="paginationReactive.itemCount"
        :page="paginationReactive.page" :page-size="paginationReactive.pageSize"
        @update:page="paginationReactive.onChange" @update:page-size="paginationReactive.onUpdatePageSize"
        show-size-picker show-quick-jumper :suffix="() => '页'">
        <template #prefix>
          <span style="font-size: 14px;"> 共{{ paginationReactive.itemCount }}条</span>
        </template>
      </NPagination>
    </template>
  </TableView>
</template>

<style scoped lang="scss">
.table {
  height: 100%;
  padding: 29px 30px 42px;
}
</style>
